//
//  RouNotifier.swift
//
//

import UIKit

//MARK: - 通知创建和使用
private let notifi = NotificationCenter.default

public func addN(_ observer: Any, _ selector: Selector, _ name: NSNotification.Name, _ object: Any? = nil) {
    notifi.addObserver(observer, selector: selector, name: name, object: object)
}

public func removeN(_ observer: Any, _ name: NSNotification.Name, _ object : AnyObject? = nil) {
    notifi.removeObserver(observer, name: name, object: object)
}

public func removeAllN(_ observer: Any) {
    notifi.removeObserver(observer)
}

public func postN(_ name: NSNotification.Name, _ object: Any? = nil, _ userInfo: [AnyHashable : Any]? = nil) {
    notifi.post(name: name, object: object, userInfo: userInfo)
}

public func notifiName(_ name: String) -> NSNotification.Name {
    return NSNotification.Name(rawValue: name)
}


//MARK: --- 通知协议
public protocol Notifier :RawRepresentable {
    associatedtype NotificationItem : RawRepresentable
}

public extension Notifier where NotificationItem.RawValue == String{
    /// 添加通知
    ///
    /// - Parameters:
    ///   - observer: 监听对象
    ///   - selector: 接收通知后处理的方法
    ///   - notiItem: 枚举值
    ///   - object: 传递的数据信息
    static func addObserver(observer: AnyObject ,selector : Selector ,notiItem : NotificationItem , object : AnyObject? = nil){
        addN(observer, selector, notifiName(notiItem.rawValue), object)
    }
    
    /// 移除通知
    ///
    /// - Parameters:
    ///   - observer: 对象
    ///   - notiItem: 枚举值
    ///   - object: 发送消息
    static func removeObserver(observer : AnyObject ,  notiItem : NotificationItem, object : AnyObject? = nil){
        removeN(observer, notifiName(notiItem.rawValue), object)
    }
    
    /// post notification
    ///
    /// - Parameters:
    ///   - notiItem: enum items
    ///   - object: object
    ///   - userInfo: info wanted to post
    func postNotification(object : Any? = nil ,userInfo : [AnyHashable : Any]? = nil){
        postN(notifiName(self.rawValue as! String), object, userInfo)
    }
    
    static func removeAllObserver(observer : AnyObject){
        removeAllN(observer)
    }
    
}

/// 系统相关通知
public enum SystemNotifer : String , Notifier {
    public typealias NotificationItem = SystemNotifer
    case EnterBackground , EnterForeground // 程序后台前台监控
    case KeyboardShow, KeyboardHide  //键盘显示与消失
}

/// 用户登录相关通知
public enum UserNotifer : String , Notifier {
    public typealias NotificationItem = UserNotifer
    case UserLogin , UserLogout         // 用户登录，登出
}
